﻿using IRepository;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Model;

namespace Repository
{
    public class BaseRepository_0<T> : IBaseRepository<T> where T : class
    {
        private  Dictionary<string, DbContext> dicDbContext = null;
        private  object objLock = null;

        public BaseRepository_0()
        {
            dicDbContext = new Dictionary<string, DbContext>();
            objLock = new object();
        }

        protected DbContext GetDbContext(string constr)
        {
           return new MyDbContext(constr);
        }

        public int Add(T t, string constr)
        {
            var context = GetDbContext(constr);
            context.Add(t);
            return context.SaveChanges();
        }

        public IQueryable<T> Find(Expression<Func<T, bool>> expression, string constr, bool isUpdate = false)
        {
            isUpdate = true;
            var context = GetDbContext(constr);
            //if (expression != null)
            //    return context.Set<T>().Where(expression);
            //else
            //    return context.Set<T>();
            if (expression != null)
            {
                return isUpdate ? context.Set<T>().AsNoTracking().Where(expression) : context.Set<T>().Where(expression);
            }
            else
                return isUpdate ? context.Set<T>().AsNoTracking() : context.Set<T>();
        }

        public int Remove(T t, string constr)
        {
            var context = GetDbContext(constr);
            context.Set<T>();
            context.Remove(t);
            return context.SaveChanges();
        }

        public int Update(T t, string constr)
        {
            var context = GetDbContext(constr);
            var enty = context.Entry<T>(t);
            enty.State = EntityState.Modified;
            return context.SaveChanges();
        }

        public T Find(int id, string constr)
        {
            throw new NotImplementedException();
        }
        public IEnumerable<T> GetAll(string constr)
        {
            return Find(null, constr).ToList();
        }
    }
}
